package com.biodiv.client.loadBalan.strategy;

import com.biodiv.client.registry.ClientInstanceManager;
import com.biodiv.common.instance.ServiceInstance;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: tianquan
 * @date: 2024-11-04  12:23
 * @Description: 轮询负载均衡器
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    @Override
    public ServiceInstance choose(String serviceName) {
        // 获取指定的服务列表
        Set<ServiceInstance> instance = ClientInstanceManager.getInstance(serviceName);
        if (instance == null || instance.isEmpty()) {
            return null;
        }
        // 轮询选择
        int index = ATOMIC_INTEGER.getAndIncrement() & Integer.MAX_VALUE;
        List<ServiceInstance> collect = instance.stream()
                .sorted(Comparator.comparingInt(ServiceInstance::getPort))
                .collect(Collectors.toList());
        return collect.get(index % instance.size());
    }

}
